package com.lp.sys.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.iframework.commons.domain.enums.HttpStatusCode;
import org.iframework.commons.domain.enums.RecordStatus;
import org.iframework.commons.domain.order.Order;
import org.iframework.commons.domain.pager.Pager;
import org.iframework.commons.util.fast.L;
import org.iframework.commons.util.fast.V;
import org.iframework.support.spring.hibernate.service.BaseServiceSupport;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.lp.business.domain.JsonResultModel;
import com.lp.business.model.Menu;
import com.lp.business.model.MenuMethod;
import com.lp.sys.controller.base.BaseController;

/**
 * 系统菜单控制器
 * 
 * @author lipeng
 * 
 */
@Controller
@RequestMapping("/admin/menuMethod")
public class MenuMethodController extends BaseController<MenuMethod, String> {
	
	@Resource(name = "menuMethodService")
	@Override
	public void setBaseServiceSupport(BaseServiceSupport<MenuMethod, String> baseService) {
		super.setBaseServiceSupport(baseService);
	}

	/**
	 * 加载分页列表数据
	 */
	@RequestMapping(value = "list", method = { RequestMethod.POST, RequestMethod.GET })
	public ModelAndView list(HttpServletRequest request,HttpServletResponse response, MenuMethod model) {
		ModelAndView modelAndView = new ModelAndView("/menuMethod/pageList");
		model.setStatus(RecordStatus.AVAILABLE);
		Pager pager = this.getPager(request);
		Order order = this.getOrder(request);
		List<MenuMethod> models = this.baseService.findByModel(model, order, pager);
		modelAndView.addObject("models", models);
		modelAndView.addObject("page", pager);
		return modelAndView;
	}
	
	/**
	 * 进行保存操作
	 */
	@RequestMapping(value = "save", method = { RequestMethod.POST, RequestMethod.GET })
	public void save(HttpServletRequest request, HttpServletResponse response, MenuMethod model, BindingResult result, SessionStatus status) {
		String menuId = request.getParameter("menuLookup.id");
		if (V.isNotEmpty(menuId)) {
			Menu m = new Menu();
			m.setId(menuId);
			model.setMenu(m);
		}
		try {
			String isCreated = request.getParameter("isCreated");
			// 自动生成菜单方法
			if (isCreated != null && isCreated.equals("1")) {
				Map<String, String> methodNameMap=new HashMap<String, String>();
				methodNameMap.put("index", "查询");
				methodNameMap.put("save", "保存");
				methodNameMap.put("update", "更新");
				methodNameMap.put("delete", "删除");
				methodNameMap.put("add", "添加");
				methodNameMap.put("edit", "编辑");
				methodNameMap.put("detail", "详情");
				methodNameMap.put("lookup", "查找带回");
				methodNameMap.put("suggest", "查找建议");
				methodNameMap.put("batchDelete", "批量删除");
				methodNameMap.put("foreverdelete", "永久删除");
				methodNameMap.put("updateStatus", "更新状态");
				methodNameMap.put("updateSort", "更新排序");
				methodNameMap.put("lookUpCallBackObj", "查找带回回调");
				
				for (Entry<String, String> entry : methodNameMap.entrySet()) {
				 MenuMethod menuMethod = new MenuMethod();
					menuMethod.setMenu(model.getMenu());
					menuMethod.setMethodTagName(entry.getKey());
					menuMethod.setMethodName(entry.getValue());
					menuMethod.setIsSelected(1);
					menuMethod.setStatus(RecordStatus.AVAILABLE);
					this.baseService.save(menuMethod);
				}
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "新建保存操作成功").toSysJsonString(), response);
				} else {
					if (V.isNotEmpty(this.baseService.save(model))) {
						renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "新建保存操作成功").toSysJsonString(), response);
						return;
					} else {
						renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "新建保存操作失败").toSysJsonString(), response);
						return;
					}
				}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
			return;
		}
	}

	/**
	 * 进行更新操作
	 */
	@RequestMapping(value = "update", method = { RequestMethod.POST, RequestMethod.GET })
	public void update(HttpServletRequest request, HttpServletResponse response, MenuMethod model, BindingResult result, SessionStatus status) {
		//校验是否传入id信息
		if (V.isEmpty(model.getId())) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "ID必须填写").toSysJsonString(), response);
			return;
		}
		//校验是否存在相应数据
		MenuMethod menuMethod =  this.baseService.get(model.getId());
		if (V.isEmpty(menuMethod)) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "找不到需要更新的数据").toSysJsonString(), response);
			return;
		}
		//执行更新逻辑
		String menuId = request.getParameter("menuLookup.id");
		if (V.isNotEmpty(menuId)) {
			Menu m = new Menu();
			m.setId(menuId);
			model.setMenu(m);
		}
		try {
			if (this.baseService.update(model)) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "更新修改操作成功").toSysJsonString(), response);
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "更新修改操作失败").toSysJsonString(), response);
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
		}
	}

	/**
	 * 进行更新记录是否选择操作（默认，注意：更新选择字段时实体对象必须要有选择字段）
	 */
	@RequestMapping(value = "updateSelected", method = { RequestMethod.POST, RequestMethod.GET })
	public void updateSelected(HttpServletRequest requerst, HttpServletResponse response, MenuMethod model) {
		try {
			if (this.baseService.update(model)) {
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "更新修改操作成功").toSysJsonString(), response);
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "更新修改操作失败").toSysJsonString(), response);
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试").toSysJsonString(), response);
		}
	}

	/**
	 * 进行批量删除操作
	 */
	@RequestMapping(value = "batchDelete", method = { RequestMethod.POST, RequestMethod.GET })
	public void batchDelete(HttpServletRequest request, HttpServletResponse response) {
		//1.执行必填校验
		String[] ids = request.getParameterValues("ids[]");
		if (V.isEmpty(ids)) {
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "请选择需要删除的信息").toSysJsonString(), response);
			return;
		}
		//2.执行删除
		try {
			Collection<MenuMethod> models = new ArrayList<MenuMethod>();
			for (String id : ids) {
				//校验是否有此id的数据
				MenuMethod model = this.baseService.get(id);
				if(V.isEmpty(model)){
					renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "删除失败，未找到需要删除的数据").toSysJsonString(), response);
					return;
				}
				models.add(model);
			}
			if(this.baseService.deleteAllVirtual(models)){
				renderJson(new JsonResultModel(HttpStatusCode.SUCCESS.getDesc(), "批量删除操作成功").toSysJsonString(), response);
			} else {
				renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "批量删除操作失败").toSysJsonString(), response);
			}
		} catch (Exception e) {
			L.e(e.getMessage(), e);
			renderJson(new JsonResultModel(HttpStatusCode.FAILURE.getDesc(), "系统繁忙，请稍候再试。").toSysJsonString(), response);
		}
	}

}
